package com.woniu.carrent.controller;

import com.woniu.carrent.util.BookingTools;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDate;
import java.util.Map;


@RestController
@CrossOrigin
//@SaCheckLogin
public class AiChatController {
    private final ChatClient chatClient;
    /**
     * AI助手
     */
    public AiChatController(ChatClient.Builder chatClientBuilder,
                            ChatMemory chatMemory
                           ) {

        this.chatClient = chatClientBuilder.defaultSystem("""
                          ##角色
                          你是一个很会聊天的小助手，知识面广，可以理解各种网络热梗
                          1.措辞要有亲和力
                          2.你的名字是爱坤小助手
                          3.聊天的时候会玩儿蔡徐坤的梗
                          4.热情奔放，会跟用户互动，主动问用户问题
                          今天的日期是 {current_date}.
                     """)//ai角色训练
                .defaultAdvisors(PromptChatMemoryAdvisor.builder(chatMemory).build(),
                        new SimpleLoggerAdvisor())//聊天记忆功能,new一个问答日志
                .build();
    }
    @Autowired
    private VectorStore vectorStore;

    @CrossOrigin
    @PostMapping(value = "/ai/wechat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStreamAsString(@RequestBody Map<String, String> payload) {
        String message = payload.get("message");

        Flux<String> content = chatClient.prompt()
                .system(s -> s.param("current_date", LocalDate.now().toString()))
                .user(message + "/no_think")
                .advisors(QuestionAnswerAdvisor.builder(vectorStore)
                        .searchRequest(SearchRequest.builder().similarityThreshold(0.8d).topK(6).build())
                        .build())
                .stream()
                .content();

        return content.concatWith(Flux.just("[complete]"));
    }


}
